package sum.book.common.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import sum.book.common.web.filter.HeaderValueFilter;

import javax.annotation.Resource;

/**
 * @Auther: ZhangGN
 * @Description: Token的存储策略
 * @Date 2022/11/21 16:53
 **/
@Configuration
public class BeanConfig {

    String PROJECT_OAUTH_ACCESS = "book:access:";

    @Resource
    RedisConnectionFactory redisConnectionFactory;


    @Bean
    HeaderValueFilter headerValueFilter() {
        return new HeaderValueFilter();
    }

    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix(PROJECT_OAUTH_ACCESS);
        return redisTokenStore;
    }

    @Bean
    public ResourceServerTokenServices resourceServerTokenServices() {
        //如果资源服和认证服在一起可以使用DefaultTokenServices进行本地检验
        //使用远程服务请求授权服务器校验token,必须指定校验token 的url、client_id，client_secret
        DefaultTokenServices service = new DefaultTokenServices();
        service.setTokenStore(tokenStore());
        return service;
    }
}


